package User;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.time.LocalDateTime;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class LibraryGUI extends JFrame {
    private JTextField authorField;
    private JTextField titleField;
    private JTextField searchField;
    private JTable table;
    private JScrollPane scrollPane;
    private Library library;
    private String userLogin;
    private LlbraryDB libraryDB;
    private BookTableModel bookTableModel;
    private JPanel contentPanel;

    private class BookTableModel extends AbstractTableModel {
        private List<Book> books;
        private String[] columnNames = {"Title", "Author", "Actions"};
        public BookTableModel(List<Book> books) {
            this.books = new ArrayList<>(books);
        }
        @Override
        public int getRowCount() {
            return books.size();
        }
        @Override
        public int getColumnCount() {
            return columnNames.length;
        }
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Book book = books.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return book.getTitle();
                case 1:
                    return book.getWriter();
                case 2:
                    return "Borrow";
                default:
                    return null;
            }
        }
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return getValueAt(0, columnIndex).getClass();
        }
        private void updateBooks(List<Book> newBooks) {
            this.books = new ArrayList<>(newBooks);
            fireTableDataChanged();
        }
    }
    public LibraryGUI(String userLogin) {
        this.userLogin = userLogin;
        setTitle("Library Book Search");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPanel = new JPanel(new BorderLayout()); // 初始化内容面板并设置布局

        libraryDB = new LlbraryDB();
        library = new Library();

        // 设置组件
        JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10));
        panel.add(new JLabel("Author:"));
        authorField = new JTextField(20);
        panel.add(authorField);

        panel.add(new JLabel("Title:"));
        titleField = new JTextField(20);
        panel.add(titleField);

        panel.add(new JLabel("Search (by any field):"));
        searchField = new JTextField(20);
        panel.add(searchField);

        JPanel buttonPanel = new JPanel();
        JButton searchButton = new JButton("Search");
        searchButton.addActionListener(e -> searchBooks());
        buttonPanel.add(searchButton);

        JButton quickSearchButton = new JButton("Quick Search");
        quickSearchButton.addActionListener(e -> quickSearchBooks());
        buttonPanel.add(quickSearchButton);

        contentPanel.add(panel, BorderLayout.NORTH);
        contentPanel.add(buttonPanel, BorderLayout.CENTER);

        table = new JTable();
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setPreferredScrollableViewportSize(new Dimension(700, 400));
        scrollPane = new JScrollPane(table);
        contentPanel.add(scrollPane, BorderLayout.SOUTH);
        bookTableModel = new BookTableModel(new ArrayList<>());
        table.setModel(bookTableModel);
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int row = table.getSelectedRow();
                if (row >= 0) {
                    Book book = bookTableModel.books.get(row);
                    showBorrowDialog(book);
                }
            }
        });
        for (int i = 0; i < bookTableModel.getColumnCount(); i++) {
            TableColumn column = table.getColumnModel().getColumn(i);
            if (i == 2) {
                column.setPreferredWidth(100);
            } else {
                column.setPreferredWidth(200); // 其他列宽度
            }
        }
        setContentPane(contentPanel);
        setVisible(true);
    }
    private void searchBooks() {
        String authorKeyword = authorField.getText().trim();
        String titleKeyword = titleField.getText().trim();
        List<Book> resultList = new ArrayList<>();
        if (authorKeyword.isEmpty() && titleKeyword.isEmpty()) {
            // 不执行查询
        } else if (authorKeyword.isEmpty()) {
            resultList = library.searchByTitle(titleKeyword);
        } else if (titleKeyword.isEmpty()) {
            resultList = library.searchByAuthor(authorKeyword);
        } else {
            resultList = library.searchByAuthorAndTitle(authorKeyword, titleKeyword);
        }
        updateResultPanel(resultList);
    }
    private void quickSearchBooks() {
        String searchKeyword = searchField.getText().trim();
        List<Book> resultList = library.searchByAnyField(searchKeyword);
        updateResultPanel(resultList);
    }
    public void updateResultPanel(List<Book> resultList) {
        bookTableModel.updateBooks(resultList);
    }
    private void showBorrowDialog(Book book) {
        int result = JOptionPane.showConfirmDialog(null, "Do you want to borrow \"" + book.getTitle() + "\" by " + book.getWriter() + "?", "Borrow Book", JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            borrowBook(book);
        }
    }
    private void borrowBook(Book book) {
        LocalDateTime currentTime = LocalDateTime.now();
        libraryDB.borrowBook(userLogin, book.toString(), currentTime);
        JOptionPane.showMessageDialog(null, "Book borrowed successfully!");
        List<Book> newBooks = new ArrayList<>(bookTableModel.books);
        newBooks.remove(book);
        bookTableModel.updateBooks(newBooks);
    }

    public JPanel getContentPanel() {
        return contentPanel;
    }

  /*public void refreshBookList() {
        List<Book> allBooks = library.loadBooksFromDatabase();  // 假设Library类有获取所有书籍的合适方法，你可能需要实现它
        bookTableModel.updateBooks(allBooks);
    }*/
    // 获取内容面板的方法
}